package com.gitee.francis.lw.form.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.databind.JavaType;
import com.gitee.francis.lw.form.model.request.FormGroupRItemRequestDTO;
import com.gitee.francis.lw.form.model.response.ControlAllResponseDTO;
import com.gitee.francis.lw.form.model.response.ControlAttrAllResponseDTO;
import com.gitee.francis.lw.form.model.response.FormGroupRItemGetResponseDTO;
import com.gitee.francis.lw.form.model.response.FormGroupRItemListResponseDTO;
import com.gitee.francis.lw.form.model.search.FormGroupRItemSearchDTO;
import com.gitee.francis.lw.form.service.IControlAttrService;
import com.gitee.francis.lw.form.service.IControlService;
import com.gitee.francis.lw.form.service.IFormGroupRItemService;
import com.gitee.francis.lw.form.service.IFormItemService;
import com.gitee.francis.lw.mapper.model.custom.FormGroupRItemCustomDO;
import com.gitee.francis.lw.mapper.model.db.ControlAttrDO;
import com.gitee.francis.lw.mapper.model.db.ControlDO;
import com.gitee.francis.lw.mapper.model.db.FormGroupRItemDO;
import com.gitee.francis.lw.mapper.model.db.FormItemDO;
import com.github.pagehelper.PageInfo;
import com.hzlemone.controller.AbstractController;
import com.hzlemone.enums.ResponseStatusEnum;
import com.hzlemone.response.ResponseDTO;
import com.hzlemone.response.ResponsePageDTO;
import com.hzlemone.utils.JsonUtil;

/**
 * @ClassName ElseClassifyController.java
 * @Description
 * @author Francis.LW
 * @date 2018年1月5日
 **/
@RestController
@RequestMapping("/admin/form/group/r/item")
@Api(value = "表单组关联表单项 REST API", description = "表单组关联表单项 REST API")
public class FormGroupRItemController
		extends
		AbstractController<FormGroupRItemDO, FormGroupRItemCustomDO, FormGroupRItemSearchDTO, FormGroupRItemListResponseDTO, FormGroupRItemRequestDTO, FormGroupRItemGetResponseDTO> {

	@Autowired
	IControlService controlService;

	@Autowired
	IControlAttrService controlAttrService;

	@Autowired
	IFormGroupRItemService formGroupRItemService;

	@Autowired
	IFormItemService formItemService;

	@ApiOperation(value = "获取表单组关联表单项列表", notes = "获取表单组关联表单项列表")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "currentpage", value = "当前页数", defaultValue = "1", paramType = "query", required = true, dataType = "int"),
			@ApiImplicitParam(name = "pagesize", value = "每页记录数", defaultValue = "10", paramType = "query", required = true, dataType = "int") })
	@RequestMapping(value = "/list", method = RequestMethod.POST)
	@Override
	public ResponseDTO list(
			@RequestParam(name = "currentpage", defaultValue = "1") int currentPage,
			@RequestParam(name = "pagesize", defaultValue = "10") int pageSize,
			@RequestBody(required = false) FormGroupRItemSearchDTO search) {
		ResponseDTO responseDTO = new ResponseDTO();

		try {
			FormGroupRItemCustomDO param = new FormGroupRItemCustomDO();

			// 设置搜索参数
			if (search != null) {
				param = collectionMapperDecorator.map(search,
						FormGroupRItemCustomDO.class);
			}
			// 设置分页参数
			param.setPage(currentPage);
			param.setRows(pageSize);

			PageInfo<FormGroupRItemCustomDO> pageInfo = service
					.listByPage(param);

			ResponsePageDTO<FormGroupRItemListResponseDTO> responsePageDTO = new ResponsePageDTO<FormGroupRItemListResponseDTO>();
			List<FormGroupRItemListResponseDTO> list = new ArrayList<FormGroupRItemListResponseDTO>();
			if (currentPage <= pageInfo.getPages()) {
				list = (List<FormGroupRItemListResponseDTO>) collectionMapperDecorator
						.mapCollection(pageInfo.getList(),
								FormGroupRItemListResponseDTO.class);
			}

			responsePageDTO.setList(list);
			responsePageDTO.setTotalRecord(pageInfo.getTotal());

			responseDTO.setCode(ResponseStatusEnum.SUCCESS.getCode());
			responseDTO.setMessage(ResponseStatusEnum.SUCCESS.getMessage());
			responseDTO.setData(responsePageDTO);

			logger.info("信息列表:" + JsonUtil.toJson(responseDTO));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return responseDTO;
	}

	@ApiOperation(value = "获取表单组关联表单项详情", notes = "获取表单组关联表单项详情")
	@ApiImplicitParam(name = "id", value = "信息id", paramType = "path", required = true, dataType = "String")
	@RequestMapping(value = "/get/{id}", method = RequestMethod.GET)
	@Override
	public ResponseDTO getById(@PathVariable("id") String id) {

		ResponseDTO responseDTO = new ResponseDTO();
		FormGroupRItemGetResponseDTO formGroupRItemGetResponseDTO = new FormGroupRItemGetResponseDTO();
		FormGroupRItemDO formGroupRItemDO = formGroupRItemService.getById(id);

		FormItemDO formItemDO = formItemService.getById(formGroupRItemDO
				.getFormItemId());
		formGroupRItemGetResponseDTO = collectionMapperDecorator.map(
				formItemDO, FormGroupRItemGetResponseDTO.class);
		formGroupRItemGetResponseDTO.setItemSort(formGroupRItemDO
				.getHzLemonEGroupItemSort());
		List<ControlAllResponseDTO> controlAllResponseDTOs = new ArrayList<ControlAllResponseDTO>();
		HashMap<String, Object> param = new HashMap<String, Object>();

		List<String> controlText = Arrays.asList("range", "selectItems");
		List<ControlDO> controlDOs = controlService.listBy(param);

		for (ControlDO control : controlDOs) {
			ControlAllResponseDTO controlAllResponseDTO = collectionMapperDecorator
					.map(control, ControlAllResponseDTO.class);

			List<ControlAttrAllResponseDTO> controlAttrAllResponseDTOs = new ArrayList<ControlAttrAllResponseDTO>();
			HashMap<String, Object> attrParam = new HashMap<String, Object>();
			attrParam.put("controlId", control.getId());
			List<ControlAttrDO> controlAttrDOs = controlAttrService
					.listBy(attrParam);
			if (controlAttrDOs != null && controlAttrDOs.size() != 0) {
				controlAttrAllResponseDTOs = (List<ControlAttrAllResponseDTO>) collectionMapperDecorator
						.mapCollection(controlAttrDOs,
								ControlAttrAllResponseDTO.class);

				for (ControlAttrAllResponseDTO caa : controlAttrAllResponseDTOs) {
					if (controlText.contains(caa.getHzLemonEControlAttrCode())) {
						List<HashMap<String, Object>> val = (List<HashMap<String, Object>>) getAttrValue(
								formItemDO.getHzLemonEFormItemAttr(),
								caa.getHzLemonEControlAttrCode());
						List<String> valList = new ArrayList<String>();
						if (val != null) {
							for (HashMap<String, Object> v : val) {
								valList.add(String.valueOf(v.get("name")));
							}
							caa.setValue(StringUtils.join(valList, ";"));
						}
					} else {
						caa.setValue(getAttrValue(
								formItemDO.getHzLemonEFormItemAttr(),
								caa.getHzLemonEControlAttrCode()));
					}
				}
			}
			controlAllResponseDTO.setAttr(controlAttrAllResponseDTOs);
			controlAllResponseDTOs.add(controlAllResponseDTO);
		}
		formGroupRItemGetResponseDTO
				.setControlAllResponseDTOs(controlAllResponseDTOs);

		responseDTO.setCode(ResponseStatusEnum.SUCCESS.getCode());
		responseDTO.setMessage(ResponseStatusEnum.SUCCESS.getMessage());
		responseDTO.setData(formGroupRItemGetResponseDTO);
		return responseDTO;
	}

	private Object getAttrValue(String itemAttr, String key) {
		JavaType javaType = JsonUtil.getCollectionType(ArrayList.class,
				HashMap.class);
		List<HashMap<String, Object>> attrList = JsonUtil.fromJson(itemAttr,
				javaType);

		for (HashMap<String, Object> attr : attrList) {
			if (attr.get("key").equals(key)) {
				return attr.get("value");
			}
		}

		return null;
	}

	@ApiOperation(value = "删除表单组关联表单项", notes = "删除表单组关联表单项，可进行单条或批量删除")
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	@Override
	public ResponseDTO remove(@RequestBody String[] ids) {
		return super.remove(ids);
	}
}
